package com.fywsy.fyweb.strategy;

import com.fywsy.fyweb.entity.SendItem;
import org.springframework.stereotype.Component;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.util.Collections;
import java.util.List;
import java.time.Instant;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;

/**
 * 游戏后台实现类
 * 注解gameId对应数据库游戏id
 * 注解GongnengMethod对应数据库功能id
 */
@Component
@GameId(10)
public class AMenghuanGameStrategy extends BaseGameStrategy {

    private static String cookie;
    private static long cookieExpireTime; // Cookie过期时间戳
    private static final long COOKIE_EXPIRE_HOURS = 10; // Cookie有效期（小时）
    public static final String LOGIN = "http://110.40.83.224:30388/login/ajax.php?act=login";
    public static final String SEND_ITEM = "http://110.40.83.224:30388/login/admin/ajax.php?act=gm&gmtype=6";
    public static final String SEND_PET = "http://110.40.83.224:30388/login/admin/ajax.php?act=gm&gmtype=4";
    public static final String CLEAR = "http://110.40.83.224:30388/login/admin/ajax.php?act=gm&gmtype=1";

    public static final String PAY = "http://110.40.83.224:30388/login/admin/ajax.php?act=gm&gmtype=2";
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    private boolean isCookieExpired() {
        if (cookie == null) {
            return true;
        }
        long currentTime = Instant.now().getEpochSecond();
        return currentTime >= cookieExpireTime;
    }

    private String sendRequest(String url, MultiValueMap<String, String> body) {
        if (isCookieExpired()) {
            login();
        }
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.set("X-Requested-With", "XMLHttpRequest");
        headers.set("Cookie", cookie);

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);
        
        try {
            ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                String.class
            );
            // 解析JSON响应，只返回msg字段
            Map<String, Object> responseMap = objectMapper.readValue(response.getBody(), Map.class);
            return (String) responseMap.get("msg");
        } catch (Exception e) {
            return "请求失败：" + e.getMessage();
        }
    }

    @GongnengMethod(1001)
    public String mail(SendItem item) {
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("serverid", "1");
        body.add("roleid", item.uid);
        body.add("itemid", item.itemId);
        body.add("number", item.number);
        return sendRequest(SEND_ITEM, body);
    }

    @GongnengMethod(1002)
    public String pet(SendItem item) {
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("serverid", "1");
        body.add("roleid", item.uid);
        body.add("petid", item.itemId);
        body.add("number", item.number);
        return sendRequest(SEND_PET, body);
    }

    @GongnengMethod(1003)
    public String clear(SendItem item) {
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("serverid", "1");
        body.add("roleid", item.uid);
        body.add("caozuo", "5");
        return sendRequest(CLEAR, body);
    }

    @GongnengMethod(1004)
    public String pay(SendItem item) {
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("serverid", "1");
        body.add("roleid", item.uid);
        body.add("caozuo", item.itemId);
        body.add("number", item.number);
        return sendRequest(PAY, body);
    }

    public String login() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.set("X-Requested-With", "XMLHttpRequest");

        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("username", "admin");
        body.add("password", "diyao88");

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);
        
        try {
            ResponseEntity<String> response = restTemplate.exchange(
                LOGIN,
                HttpMethod.POST,
                requestEntity,
                String.class
            );
            
            List<String> cookies = response.getHeaders().get("Set-Cookie");
            if (cookies != null && !cookies.isEmpty()) {
                StringBuilder cookieBuilder = new StringBuilder();
                for (String cookie : cookies) {
                    if (cookieBuilder.length() > 0) {
                        cookieBuilder.append("; ");
                    }
                    cookieBuilder.append(cookie.split(";")[0]);
                }
                cookie = cookieBuilder.toString();
                // 设置Cookie过期时间（当前时间 + 10小时）
                cookieExpireTime = Instant.now().getEpochSecond() + (COOKIE_EXPIRE_HOURS * 3600);
                return "登录成功";
            }
            return "登录失败：未获取到Cookie";
        } catch (Exception e) {
            return "登录失败：" + e.getMessage();
        }
    }

    public static void main(String[] args) {
        AMenghuanGameStrategy strategy = new AMenghuanGameStrategy();
        
        // 测试发送物品
        SendItem item = new SendItem();
        item.uid = "4102";
        item.itemId = "4";
        item.number = "111123";
        System.out.println("发送物品结果：" + strategy.pay(item));
        
//        // 测试发送宠物
//        SendItem pet = new SendItem();
//        pet.uid = "4102";
//        pet.itemId = "510953";
//        pet.number = "1";
//        System.out.println("发送宠物结果：" + strategy.pet(pet));
//
//        // 测试清除
//        SendItem clear = new SendItem();
//        clear.uid = "4102";
//        System.out.println("清除结果：" + strategy.clear(clear));
    }
}

